package com.sellspringcloud.server.controller;

import com.sellspringcloud.server.VO.ResultVO;
import com.sellspringcloud.server.constans.UserConstans;
import com.sellspringcloud.server.dataobject.UserInfo;
import com.sellspringcloud.server.enums.UserEnum;
import com.sellspringcloud.server.enums.UserRoleEnum;
import com.sellspringcloud.server.exception.UserException;
import com.sellspringcloud.server.service.UserService;
import com.sellspringcloud.server.utils.CookiesUtil;
import com.sellspringcloud.server.utils.ResultVOUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.sellspringcloud.server.constans.UserConstans.COOKIE_EXPIRE;
import static com.sellspringcloud.server.constans.UserConstans.REDIS_EXPIRE;

/**
 * @author
 * @create 2019-08-10 17:12
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/getUserByOpenid")
    public ResultVO getUserByOpenId(@RequestParam("openid") String openId) {
        UserInfo user = userService.getUserByOpenId(openId);
        return ResultVOUtil.success(user);
    }

    /**
     * 通过openid获取用户，若是买家，则将openId加入cookie中
     *
     * @param openId
     * @param response
     * @return
     */
    @GetMapping("/login/buyer")
    public ResultVO loginForBuyer(@RequestParam("openid") String openId,
                                  HttpServletResponse response) {
        UserInfo user = userService.getUserByOpenId(openId);
        if (user == null) {
            throw new UserException(UserEnum.USER_NOT_EXIT.getCode(),
                    UserEnum.USER_NOT_EXIT.getMsg());
        }

        if (UserRoleEnum.BUYER.getCode() != user.getRole()) {
            throw new UserException(UserEnum.USER_ROLE_ERORR.getCode(),
                    UserEnum.USER_ROLE_ERORR.getMsg());
        }

        CookiesUtil.addCookie(response, UserConstans.USER_OPENID, user.getOpenid(), COOKIE_EXPIRE);
        return ResultVOUtil.success(true);
    }

    /**
     * 通过openid获取用户，若是卖家，则将token加入cookie中,并加入redis中
     *
     * @param openId
     * @param response
     * @return
     */
    @GetMapping("/login/seller")
    public ResultVO loginForSeller(@RequestParam("openid") String openId,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {
        String redisKey = String.format(UserConstans.USER_TOKEN, openId);
        String cookie = CookiesUtil.getCookie(request, UserConstans.USER_TOKEN);
        if (StringUtils.isNotBlank(cookie) &&
                Objects.equals(cookie, redisTemplate.opsForValue().get(redisKey))) {
            return ResultVOUtil.success(true);
        }

        UserInfo user = userService.getUserByOpenId(openId);
        if (user == null) {
            throw new UserException(UserEnum.USER_NOT_EXIT.getCode(),
                    UserEnum.USER_NOT_EXIT.getMsg());
        }

        if (UserRoleEnum.SELLER.getCode() != user.getRole()) {
            throw new UserException(UserEnum.USER_ROLE_ERORR.getCode(),
                    UserEnum.USER_ROLE_ERORR.getMsg());
        }

        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(redisKey, token, REDIS_EXPIRE, TimeUnit.SECONDS);

        CookiesUtil.addCookie(response, UserConstans.USER_TOKEN, token, COOKIE_EXPIRE);
        return ResultVOUtil.success(true);
    }


}